package cn.e4j.modular.api.controller;

import cn.digiwin.wx.gzh.common.WeixinGzhComm;
import cn.digiwin.wx.qyh.common.WeixinComm;
import cn.digiwin.wx.utils.CookieUtils;
import cn.digiwin.wx.utils.HttpUtil;
import cn.e4j.core.base.controller.BaseController;
import cn.e4j.core.dto.impl.Dto;
import cn.e4j.core.dto.requestDtoResolver.DtoParam;
import cn.e4j.core.dto.requestDtoResolver.DtoWapper;
import cn.e4j.core.shiro.ShiroKit;
import cn.e4j.core.util.*;
import cn.e4j.modular.crm.entity.GwaaT;
import cn.e4j.modular.crm.mapper.GwaaTMapper;
import cn.e4j.modular.system.entity.SysOrg;
import cn.e4j.modular.system.entity.SysUser;
import cn.e4j.modular.system.mapper.SysUserMapper;
import cn.e4j.modular.system.service.SysOrgService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 微信用户登录授权
 *
 * @author wenchuan.li
 * @Date 2019/4/16 16:48
 */
@Controller
@RequestMapping("/api/wx/")
@Slf4j
public class AuthController extends BaseController {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private GwaaTMapper gwaaTMapper;

    @Autowired
    private SysOrgService orgService;

    /**
     * api登录接口，通过账号密码获取token
     */
    @RequestMapping(value = "auth", method = RequestMethod.GET)
    public String auth(@DtoParam DtoWapper dtoWapper, HttpServletRequest request, HttpServletResponse response) {

        Dto map = dtoWapper.getDto();
        String code = map.getString("code");
        log.info(StringUtils.CONSOLE_FLAG3 + "获取微信企业号的认证code:{}", code);

        String account = null;
        long _times = System.currentTimeMillis();
        Map<String, String> prams = new HashMap<>();

        if (ToolUtil.isNotEmpty(code)) {
            try {
                String userUrl = WeixinComm.getWxUserInfo(code);
                String json = HttpUtil.sendHttpsRequest(userUrl, "", WeixinComm.METHOD_GET);
                log.debug(StringUtils.CONSOLE_FLAG3 + "wx-json: " + json);

                JSONObject wxUser = JSONObject.parseObject(json);

                account = wxUser.getString("UserId");

                if (ToolUtil.isEmpty(account)) {
                    log.error("001微信企业号认证失败！未获取用户授权信息");

                    userUrl = WeixinComm.getWxUserInfo(code);
                    log.debug(StringUtils.CONSOLE_FLAG3 + "wx-userUrl: {}", userUrl);

                    json = HttpUtil.sendHttpsRequest(userUrl, "", WeixinComm.METHOD_GET);
                    log.debug(StringUtils.CONSOLE_FLAG3 + "wx-json: " + json);
                    wxUser = JSONObject.parseObject(json);

                    account = wxUser.getString("UserId");

                    if (ToolUtil.isEmpty(account)) {
                        log.error("002微信企业号认证失败！未获取用户授权信息");
                        log.error(json);
                        throw new Exception("002微信企业号认证失败！未获取用户授权信息");
                    }

                }

                log.info(StringUtils.CONSOLE_FLAG3 + "wx-userId: " + account);

                //获取成员资料
                String staffUrl = WeixinComm.getWxStaff(account);
                json = HttpUtil.sendHttpsRequest(staffUrl, "", WeixinComm.METHOD_GET);
                JSONObject staff = JSONObject.parseObject(json);

                String mobile = staff.getString("mobile");
                String userName = staff.getString("name");
                String email = staff.getString("email");


                prams.put("_WX_ACCOUNT_", account);//微信账号
                prams.put("_WX_USERNAME_", userName);//用户名称
                prams.put("_WX_MOBILE_", mobile);//手机
                prams.put("_WX_AVATAR_", staff.getString("avatar"));//头像
                //prams.put("_WX_ACTI_", "N");// 审核码  N未审核 Y 表示平台已经审核通过
                prams.put("_WX_SOURCE", "Q"); //设置为Q :企业号

                //检查当前用户是否已经绑定审核过 微信平台自定义用户gwaa
                // 判断表里面是否有此人的数据，状态可以是T/N/Y/X
                GwaaT gwaaT = gwaaTMapper.selectOne(new QueryWrapper<GwaaT>()
                        .lambda()
                        //.eq(GwaaT::getGWAAENT, "80")
                        .eq(GwaaT::getGWAA001, account)
                );

                // TODO 是否加上gwaaacti=X的用户 不允许再次注册？？
                // 两个表需要放到事物里面 TODO
                if (ToolUtil.isNotEmpty(gwaaT)) {
                    if (gwaaT.getGWAAACTI().equals("X")) {
                        log.error("微信企业号：{}，账号已经被作废", account);
                        throw new Exception("账号已经被作废");
                    }
                    //prams.put("_WX_USERNAME_", gwaa.getString("gwaa002"));//用户名称
                    //prams.put("_WX_MOBILE_", gwaa.getString("gwaa004"));//手机
                } else {
                    gwaaT = new GwaaT();
                    gwaaT.setGWAAENT(AppCxt.getParam("ENT"));
                    gwaaT.setGWAA001(account);
                    gwaaT.setGWAA002(userName);
                    gwaaT.setGWAA003(account);
                    gwaaT.setGWAA004(mobile);
                    gwaaT.setGWAA006(staff.getString("gender")); //0表示未定义，1表示男性，2表示女性
                    gwaaT.setGWAA007("0");//内部员工
                    gwaaT.setGWAA010("1");//来源 企业号
                    gwaaT.setGWAA011(email);
                    gwaaT.setGWAATIME(DateUtils.getTime());
                    gwaaT.setGWAAACTI("T"); // T临时用户 N未审核用户 Y已审核用户
                    gwaaT.setGWAADATE(LocalDate.now());
                    gwaaT.setGWAAMODU(" ");
                    gwaaT.setGWAAUSER(" ");
                    gwaaT.setGWAAGRUP(" ");
                    gwaaT.setGWAAORIG(" ");
                    gwaaT.setGWAAORIU(" ");
                    gwaaTMapper.insert(gwaaT);
                }

                List<SysUser> sysUserList = sysUserMapper.selectList(new QueryWrapper<SysUser>()
                        .lambda()
                        .eq(SysUser::getACCOUNT, account)
                );
                SysUser sysUser;
                if (sysUserList.size() == 0) {
                    sysUser = new SysUser();
                    sysUser.setID(DateUtils.getDate("yyyyMMddHHmmssSSS"));
                    sysUser.setCREATE_BY("9999999999999999");//
                    sysUser.setCREATE_TIME(LocalDateTime.now());
                    sysUser.setIS_DEL("0");
                    sysUser.setACCOUNT(account);
                    sysUser.setPASSWORD(ShiroKit.md5("123456"));
                    sysUser.setNAME(userName);
                    sysUser.setSEX(gwaaT.getGWAA006());
                    //sysUser.setOrg_id_("9609052226010010");
                    sysUser.setTYPE("0");//内部员工
                    //sysUser.setSkin_("blue");
                    sysUser.setEMAIL(email);
                    sysUser.setMOBILE(mobile);
                    //sysUser.setAddress_(params.getString("gwaa13"));
                    sysUser.setSTATUS("1");
                    sysUser.setDBC(AppCxt.getParam("ENT"));
                    sysUser.setLANG("zh_CN");
                    sysUserMapper.insert(sysUser);
                    log.info("微信企业号：{}，未绑定", account);
                } else {
                    sysUser = sysUserList.get(0);
                    prams.put("_TOKEN_", JwtTokenUtil.generateToken(String.valueOf(sysUser.getID())));
                }
                prams.put("_WX_ACTI_", gwaaT.getGWAAACTI());
                prams.put("_WX_ID_", sysUser.getID());//sysUser id
                prams.put("_WX_ORGID_", sysUser.getORG_ID());//sysUser orgid
                CookieUtils.setCookie(request, response, prams);

                log.info("微信企业号：{}，已绑定登录成功", account);


                if (gwaaT.getGWAAACTI().equals("X")) {
                    log.error("微信企业号：{}，账号已经被作废", account);
                    return REDIRECT + "/html/wx/authError.html";
                }

                if (gwaaT.getGWAAACTI().equals("T")) {
                    log.error("微信企业号：{}，需要注册", account);
                    return REDIRECT + "/html/wx/register/register.html";
                }

                if (gwaaT.getGWAAACTI().equals("N")) {
                    log.error("微信企业号：{}，等待审核", account);
                    return REDIRECT + "/html/wx/waitCheckPage.html";
                }

                AppCxt.addUserInfoCache(sysUser);

                return redirectPage(sysUser);
//                return REDIRECT + "/html/wx/main.html?t=" + _times;

            } catch (Exception ex) {
                ex.printStackTrace();
                log.error("微信企业号:{},认证失败！{}", account, ex.getMessage());
                CookieUtils.removeCookie(request, response);
                return REDIRECT + "/html/wx/authError.html";
            }
        } else {
            log.error("微信企业号认证失败。未获取认证code");
            CookieUtils.removeCookie(request, response);
            return REDIRECT + "/html/wx/authError.html";
        }
    }


    /**
     * api登录接口，通过账号密码获取token
     */
    @RequestMapping(value = "authGzh", method = RequestMethod.GET)
    public String authGzh(@DtoParam DtoWapper dtoWapper, HttpServletRequest request, HttpServletResponse response) {

        Dto map = dtoWapper.getDto();
        String code = map.getString("code");
        log.info(StringUtils.CONSOLE_FLAG3 + "获取微信公众号的认证code:{}", code);

        String account = null;
        long _times = System.currentTimeMillis();
        Map<String, String> prams = new HashMap<>();

        if (ToolUtil.isNotEmpty(code)) {
            try {
                String userUrl = WeixinGzhComm.getWxUserInfo(code);
                log.info(StringUtils.CONSOLE_FLAG3 + "获取微信公众号的认证access_token:{}", userUrl);
//                String json = HttpUtil.sendHttpsRequest(userUrl, "", WeixinGzhComm.METHOD_GET);
//                log.debug(StringUtils.CONSOLE_FLAG3 + "wx-json: " + json);

                JSONObject wxUser = JSONObject.parseObject(userUrl);

                account = wxUser.getString("openid");
                log.info(StringUtils.CONSOLE_FLAG3 + "获取微信公众号的认证account:{}", account);

                if (ToolUtil.isEmpty(account)) {
                    log.error("微信公众号:{},认证失败！未获取用户授权信息",account);
                    throw new Exception("002微信公众号认证失败！未获取用户授权信息");
                }


                prams.put("_WX_ACCOUNT_", account);//微信账号
                prams.put("_WX_USERNAME_", wxUser.getString("nickname"));//用户名称
                prams.put("_WX_AVATAR_", wxUser.getString("headimgurl"));//头像
                //prams.put("_WX_ACTI_", "N");// 审核码  Y 表示平台已经审核通过
                prams.put("_WX_SOURCE","G"); //设置为G :公众号


                //检查当前用户是否已经绑定审核过 微信平台自定义用户gwaa
                // 判断表里面是否有此人的数据，状态可以是T/N/Y/X
                GwaaT gwaaT = gwaaTMapper.selectOne(new QueryWrapper<GwaaT>()
                        .lambda()
                        //.eq(GwaaT::getGWAAENT, "80")
                        .eq(GwaaT::getGWAA003, account)
                );

                // TODO 是否加上gwaaacti=X的用户 不允许再次注册？？
                // 两个表需要放到事物里面 TODO
                if (ToolUtil.isNotEmpty(gwaaT)) {
                    if (gwaaT.getGWAAACTI().equals("X")) {
                        log.error("微信公众号：{}，账号已经被作废", gwaaT.getGWAA001());
                        throw new Exception("账号已经被作废");
                    }
                } else {
                    gwaaT = new GwaaT();
                    gwaaT.setGWAAENT(AppCxt.getParam("ENT"));
                    gwaaT.setGWAA001(account);
                    gwaaT.setGWAA002(wxUser.getString("nickname"));
                    gwaaT.setGWAA003(account);
                    gwaaT.setGWAA006(wxUser.getString("sex")); //0表示未定义，1表示男性，2表示女性
                    gwaaT.setGWAA007("1");//内部员工
                    gwaaT.setGWAA010("0");//来源 公众号
                    gwaaT.setGWAATIME(DateUtils.getTime());
                    gwaaT.setGWAAACTI("T"); // T临时用户 N未审核用户 Y已审核用户
                    gwaaT.setGWAADATE(LocalDate.now());
                    gwaaTMapper.insert(gwaaT);
                }

                List<SysUser> sysUserList = sysUserMapper.selectList(new QueryWrapper<SysUser>()
                        .lambda()
                        .eq(SysUser::getACCOUNT, gwaaT.getGWAA001())
                );
                SysUser sysUser;
                if (sysUserList.size() == 0) {
                    sysUser = new SysUser();
                    sysUser.setID(DateUtils.getDate("yyyyMMddHHmmssSSS"));
                    sysUser.setCREATE_BY("9999999999999999");//
                    sysUser.setCREATE_TIME(LocalDateTime.now());
                    sysUser.setIS_DEL("0");
                    sysUser.setACCOUNT(account);
                    sysUser.setPASSWORD(ShiroKit.md5("123456"));
                    sysUser.setNAME(gwaaT.getGWAA002());
                    sysUser.setSEX(gwaaT.getGWAA006());
                    //sysUser.setOrg_id_("9609052226010010");
                    sysUser.setTYPE("1");//内部员工
                    //sysUser.setSkin_("blue");
                    sysUser.setEMAIL("");
                    sysUser.setMOBILE("");
                    //sysUser.setAddress_(params.getString("gwaa13"));
                    sysUser.setSTATUS("1");
                    sysUser.setDBC(AppCxt.getParam("ENT"));
                    sysUser.setLANG("zh_CN");
                    sysUserMapper.insert(sysUser);
                    log.info("微信公众号：{}，未绑定", account);
                } else {
                    sysUser = sysUserList.get(0);
                    prams.put("_TOKEN_", JwtTokenUtil.generateToken(String.valueOf(sysUser.getID())));
                }
                prams.put("_WX_ACTI_", gwaaT.getGWAAACTI());
                prams.put("_WX_ID_", sysUser.getID());//sysUser id
                prams.put("_WX_ORGID_", sysUser.getORG_ID());//sysUser orgid
                CookieUtils.setCookie(request, response, prams);

                log.info("微信公众号：{}，已绑定登录成功", account);


                if (gwaaT.getGWAAACTI().equals("X")) {
                    log.error("微信公众号：{}，账号已经被作废", account);
                    return REDIRECT + "/html/wx/authError.html";
                }

                if (gwaaT.getGWAAACTI().equals("T")) {
                    log.error("微信公众号：{}，需要注册", account);
                    return REDIRECT + "/html/wx/register/register.html";
                }

                if (gwaaT.getGWAAACTI().equals("N")) {
                    log.error("微信公众号：{}，等待审核", account);
                    return REDIRECT + "/html/wx/waitCheckPage.html";
                }

                AppCxt.addUserInfoCache(sysUser);

                return redirectPage(sysUser);
//                return REDIRECT + "/html/wx/main.html?t=" + _times;

            } catch (Exception ex) {
                ex.printStackTrace();
                log.error("微信公众号:{},认证失败！{}", account, ex.getMessage());
                CookieUtils.removeCookie(request, response);
                return REDIRECT + "/html/wx/authError.html";
            }
        } else {
            log.error("微信公众号认证失败。未获取认证code");
            CookieUtils.removeCookie(request, response);
            return REDIRECT + "/html/wx/authError.html";
        }
    }

    /**
     * 测试--登录用
     */
    @RequestMapping(value = "testLogin", method = RequestMethod.GET)
    public String testLogin(HttpServletRequest request, HttpServletResponse response) {

        long _times = System.currentTimeMillis();
        GwaaT gwaaT = new GwaaT();

//        SysUser sys_userPO = new SysUser();
//        sys_userPO.setID("20190522213706213");
//        sys_userPO.setACCOUNT("liwc");
//        sys_userPO.setPASSWORD("b31f72dc8449b55fbba71a552fc83bb1");
//
//        Map<String, String> prams = new HashMap<>();
//        prams.put("_WX_ACCOUNT_", "liwc");//企业微信帐号
//        prams.put("_WX_USERNAME_", "李文川");//用户名称
//        prams.put("_WX_MOBILE_", "18852462356");
//        prams.put("_WX_ID_", "20190522213706213");
//        prams.put("_WX_ORGID_", "1609052226010010");

        //销售统计echart图表演示账号
//        SysUser sys_userPO = new SysUser();
//        sys_userPO.setDBC("80");
//        sys_userPO.setID("20181024203424709");
//        sys_userPO.setACCOUNT("sam_cai");
//        sys_userPO.setPASSWORD("b696073ab241fd5503c694b29ebb0561");
//
//        Map<String, String> prams = new HashMap<>();
//        prams.put("_WX_ACCOUNT_", "sam_cai");//企业微信帐号
//        prams.put("_WX_USERNAME_", "蔡晓峰");//用户名称
//        prams.put("_WX_MOBILE_", "17858763690");
//        prams.put("_WX_ID_", "20181024203424709");
//        prams.put("_WX_ORGID_", "1609052226010010");

        SysUser sys_userPO = new SysUser();
        sys_userPO.setDBC("80");
        sys_userPO.setID("20190313163009821");
        sys_userPO.setACCOUNT("GanJia");
        sys_userPO.setPASSWORD("6c87853105168653b4254cd2689c31ff");

        Map<String, String> prams = new HashMap<>();
        prams.put("_WX_ACCOUNT_", "GanJia");//企业微信帐号
        prams.put("_WX_USERNAME_", "干佳");//用户名称
        prams.put("_WX_MOBILE_", "17366366760");
        prams.put("_WX_ID_", "20190313163009821");
        prams.put("_WX_ORGID_", "1609052226010010");

//        SysUser sys_userPO = new SysUser();
//        sys_userPO.setID("1570501380399");
//        sys_userPO.setACCOUNT("DongShuZhe");
//        sys_userPO.setPASSWORD("6c0359f2fc2565ebf1ba7934a5004bfb");
//
//        Map<String, String> prams = new HashMap<>();
//        prams.put("_WX_ACCOUNT_", "DongShuZhe");//企业微信帐号
//        prams.put("_WX_USERNAME_", "董书哲");//用户名称
//        prams.put("_WX_ID_", "1570501380399");

//        SysUser sys_userPO = new SysUser();
//        sys_userPO.setID("1571624676249");
//        sys_userPO.setACCOUNT("WangJing");
//        sys_userPO.setPASSWORD("6c0359f2fc2565ebf1ba7934a5004bfb");
//
//        Map<String, String> prams = new HashMap<>();
//        prams.put("_WX_ACCOUNT_", "WangJing");//企业微信帐号
//        prams.put("_WX_USERNAME_", "王璟");//用户名称
//        prams.put("_WX_ID_", "1571624676249");

        //sqlserver
//        SysUser sys_userPO = new SysUser();
//        sys_userPO.setID("1558491944691");
//        sys_userPO.setACCOUNT("ShiXueCheng");
//        sys_userPO.setPASSWORD("6c0359f2fc2565ebf1ba7934a5004bfb");
//
//        Map<String, String> prams = new HashMap<>();
//        prams.put("_WX_ACCOUNT_", "ShiXueCheng");//企业微信帐号
//        prams.put("_WX_USERNAME_", "施雪城");//用户名称
//        prams.put("_WX_ID_", "1558491944691");
//        prams.put("_WX_MOBILE_", "15850750729");
////
//        gwaaT.setGWAA001("shixc");
//        gwaaT.setGWAA007("0");
//        gwaaT.setGWAA008("1609052226010010");

          //oracle演示
//        SysUser sys_userPO = new SysUser();
//        sys_userPO.setID("1568187492556");
//        sys_userPO.setDBC("80");
//        sys_userPO.setACCOUNT("CaiJianYing");
//        sys_userPO.setPASSWORD("6c0359f2fc2565ebf1ba7934a5004bfb");
//
//        Map<String, String> prams = new HashMap<>();
//        prams.put("_WX_ACCOUNT_", "CaiJianYing");//企业微信帐号
//        prams.put("_WX_USERNAME_", "蔡剑英");//用户名称
//        prams.put("_WX_ID_", "1568187492556");
//
//
//        Dto user = sysUserMapper.getUser("1568187492556");//oracle
//        Dto user = sysUserMapper.getUser("1573626205994");//sqlserver


//        //oracle 演示
//        SysUser sys_userPO = new SysUser();
//        sys_userPO.setID("1570501380399");
//        sys_userPO.setDBC("80");
//        sys_userPO.setACCOUNT("DongShuZhe");
//        sys_userPO.setPASSWORD("6c0359f2fc2565ebf1ba7934a5004bfb");
//
//        Map<String, String> prams = new HashMap<>();
//        prams.put("_WX_ACCOUNT_", "DongShuZhe");//企业微信帐号
//        prams.put("_WX_USERNAME_", "董书哲");//用户名称
//        prams.put("_WX_ID_", "1570501380399");

        //oracle 演示
//        SysUser sys_userPO = new SysUser();
//        sys_userPO.setID("1558491944691");
//        sys_userPO.setDBC("80");
//        sys_userPO.setACCOUNT("shixc");
//        sys_userPO.setPASSWORD("6c0359f2fc2565ebf1ba7934a5004bfb");
//
//        Map<String, String> prams = new HashMap<>();
//        prams.put("_WX_ACCOUNT_", "shixc");//企业微信帐号
//        prams.put("_WX_USERNAME_", "施雪城");//用户名称
//        prams.put("_WX_ID_", "1558491944691");
//        prams.put("_WX_ORGID_", "1609052226010011");


        Dto user = sysUserMapper.getUser(sys_userPO.getID());
        prams.put("_TOKEN_", JwtTokenUtil.generateToken(String.valueOf(sys_userPO.getID())));
        prams.put("_WX_ACTI_", "Y");
        CookieUtils.setCookie(request,response, prams);
        return redirectPage(user);
//        return REDIRECT + "/html/wx/main.html?t=" + _times;
    }


    private String redirectPage(Dto userDto){
        String type = userDto.getString("TYPE");
        if (type.equals("0")){
            //内部员工
            SysOrg org = orgService.getById(userDto.getString("ORG_ID"));

            if (org==null)
                return REDIRECT + "/html/wx/main.html?t=" + +System.currentTimeMillis();

            if (org.getTYPE().equals("3")||org.getTYPE().equals("4")){
                //售后人员
                return REDIRECT+"/html/wx/after-sale.html?t="+System.currentTimeMillis();
            }else
                return REDIRECT+"/html/wx/businessman.html?t="+System.currentTimeMillis();

            //内部用户先统一跳到main
//            return REDIRECT + "/html/wx/main.html?t=" + System.currentTimeMillis();

        }else if (type.equals("1")){
            //外部用户
            return REDIRECT+"/html/wx/outer-user.html?t="+System.currentTimeMillis();
        }
        return REDIRECT + "/html/wx/authError.html";
//        return REDIRECT + "/html/wx/main.html?t=" + +System.currentTimeMillis();
    }


    private String redirectPage(SysUser user){
        String type = user.getTYPE();
        if (type.equals("0")){
            //内部员工
            SysOrg org = orgService.getById(user.getORG_ID());

            if (org==null)
                return REDIRECT + "/html/wx/main.html?t=" + +System.currentTimeMillis();

            if (org.getTYPE().equals("3")||org.getTYPE().equals("4")){
                //售后人员
                return REDIRECT+"/html/wx/after-sale.html?t="+System.currentTimeMillis();
            }else
                return REDIRECT+"/html/wx/businessman.html?t="+System.currentTimeMillis();

            //内部用户先统一跳到main
//            return REDIRECT + "/html/wx/main.html?t=" + System.currentTimeMillis();

        }else if (type.equals("1")){
            //外部用户
            return REDIRECT+"/html/wx/outer-user.html?t="+System.currentTimeMillis();
        }
        return REDIRECT + "/html/wx/authError.html";
    }
}

